package com.wuyu.acl.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuyu.acl.mapper.PermissionMapper;
import com.wuyu.acl.mapper.RolePermissionMapper;
import com.wuyu.acl.po.Permission;
import com.wuyu.acl.po.RolePermission;
import com.wuyu.acl.service.PermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 20556
 * @description 针对表【tb_permission(权限表)】的数据库操作Service实现
 * @createDate 2024-01-28 21:49:09
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void removeRecursion(Long id) {
        List<Permission> permissionList = permissionMapper.selectList(null);
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        getChildrenId(id, permissionList, ids);
        // 1. 递归删除权限表中的数据
        permissionMapper.deleteBatchIds(ids);
        // 2. 删除角色权限表中的数据
        if (CollUtil.isNotEmpty(ids)) {
            rolePermissionMapper.delete(new LambdaQueryWrapper<RolePermission>()
                    .in(RolePermission::getPermissionId, ids));
        }
    }

    private void getChildrenId(Long pid, List<Permission> permissionList, List<Long> ids) {
        permissionList.forEach(item -> {
            if (item.getPid().equals(pid)) {
                ids.add(item.getId());
                getChildrenId(item.getId(), permissionList, ids);
            }
        });
    }
}




